<script lang="ts" setup>
import {ref, onMounted, watchEffect} from 'vue';
import {ElMessage} from 'element-plus';
import type {Course, PageResp, PageCourse} from '@/type/course';
import {useMemberStore} from "@/stores/member.ts";
import {memberGetPageCourses} from "@/api/course";
import type {Coach} from "@/type/coach.ts";
import {memberGetCoachById} from "@/api/coach";
import {addAConsumption} from "@/api/consumption";
import type {AddConsumption} from "@/type/consumption.ts";

const memberStore = useMemberStore()
// 会员状态
const isMember = ref(memberStore.memberInfo.memberType == '会员');

const courses = ref<Course[]>([]); // 课程列表
const selectedCourse = ref<Course | null>(null); // 当前选中的课程
const selectedCourseCoach = ref<Coach | null>(null);  // 对应的教练
const dialogVisible = ref(false); // 控制弹窗显示
const searchKeyword = ref(''); // 搜索关键词
const searchType = ref<'name' | 'description'>('name'); // 搜索类型
const currentPage = ref(1); // 当前页码
const pageSize = ref(8); // 每页显示的课程数量
const total = ref(0); // 总课程数

// 获取课程数据
const fetchCourses = async () => {
  const pageInfo: PageCourse = {
    courseName: searchType.value === 'name' ? searchKeyword.value : '',
    courseDescription: searchType.value === 'description' ? searchKeyword.value : '',
    page: currentPage.value,
    pageSize: pageSize.value,
  };
  const result: PageResp = await memberGetPageCourses(pageInfo);
  if (result.code === 1) {
    total.value = result.data.total;
    courses.value = result.data.records;
  }
};

// 查看课程详情
const handleViewDetails = async (courseId: number, coachId: number) => {
  selectedCourse.value = courses.value.find((course) => course.courseId === courseId) || null;
  const result = await memberGetCoachById(coachId)
  if (result.code == 1) {
    selectedCourseCoach.value = result.data
  } else {
    ElMessage.error('教练加载失败')
  }
  dialogVisible.value = true; // 打开弹窗
};

// 关闭详情弹窗
const closeDetail = () => {
  dialogVisible.value = false; // 关闭弹窗
  selectedCourse.value = null; // 清空选中的课程
};

// 购买课程
const handleBuyCourse = async (course: Course) => {
  const consumption: AddConsumption = {
    memberId: memberStore.memberInfo.memberId,
    consumptionType: '课程',
    amount: course.coursePrice,
    relatedId: course.courseId
  }
  try {
    const result = await addAConsumption(consumption)
    if (result.code == 1) {
      ElMessage.success(`成功购买课程：${course.courseName}`);
      dialogVisible.value = false; // 关闭弹窗
      selectedCourse.value = null; // 清空选中的课程
    } else {
      ElMessage.error(`购买课程：${course.courseName}失败，请重试`);
    }
  } catch (e) {
    ElMessage.error((e as Error).message)
  }
};

// 监控查询变量-有变则重新查询
watchEffect(() => {
  fetchCourses();
});

// 组件挂载时获取数据
onMounted(() => {
  fetchCourses();
});
</script>

<template>
  <div class="course-view">
    <!-- 搜索框 -->
    <div class="search-container">
      <el-input
          v-model="searchKeyword"
          class="search-input"
          clearable
          placeholder="请输入课程名称或描述"
      />
      <el-select v-model="searchType" class="search-type" placeholder="请选择搜索类型">
        <el-option label="按课程名称搜索" value="name"/>
        <el-option label="按课程描述搜索" value="description"/>
      </el-select>
    </div>

    <!-- 课程列表 -->
    <div class="course-list-container">
      <el-row :gutter="20" class="course-list">
        <el-col
            v-for="course in courses"
            :key="course.courseId"
            :lg="6"
            :md="8"
            :sm="12"
            :xs="24"
        >
          <el-card class="course-card" @click="handleViewDetails(course.courseId, course.coachId)">
            <template #header>
              <div class="card-header">
                <img :src="course.image" alt="Course Image" class="course-image"/>
                <h3>{{ course.courseName }}</h3>
              </div>
            </template>
            <div class="info">
              <p><strong>课时:</strong> {{ course.courseDuration }} 小时</p>
              <p><strong>价格:</strong> ￥{{ course.coursePrice }}</p>
              <p><strong>描述:</strong> {{ course.courseDescription }}</p>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 分页 -->
      <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          class="pagination"
          layout="prev, pager, next"
      />
    </div>

    <!-- 课程详情弹窗 -->
    <el-dialog
        v-model="dialogVisible"
        :before-close="closeDetail"
        class="course-detail-dialog"
        title="课程详情"
        width="1000px"
    >
      <div v-if="selectedCourse" class="course-detail">
        <!-- 左侧：图片和课程内容 -->
        <div class="detail-left">
          <div class="detail-header">
            <el-image :src="selectedCourse.image" style="max-width: 300px;max-height: 200px;width: 100%;height: 200px;">
            </el-image>
            <div class="header-info">
              <h2>{{ selectedCourse.courseName }}</h2>
            </div>
          </div>
        </div>

        <!-- 中间：其他信息 -->
        <div class="detail-center">
          <div class="detail-item">
            <span class="label">价格:</span>
            <span class="value">￥{{ selectedCourse.coursePrice }}</span> <!-- 模拟数据 -->
          </div>
          <div class="detail-item">
            <span class="label">时长:</span>
            <span class="value">{{ selectedCourse.courseDuration }} 小时</span> <!-- 模拟数据 -->
          </div>
          <div class="detail-item">
            <span class="label">描述::</span>
            <span class="value">{{ selectedCourse.courseDescription }}</span> <!-- 模拟数据 -->
          </div>
        </div>

        <!-- 右侧：授课教练信息 -->
        <div class="detail-right">
          <div class="coach-info">
            <h3 class="coach-title">授课教练</h3>
            <div class="coach-details">
              <img :src="selectedCourseCoach?.avatar" alt="Coach Avatar" class="coach-avatar"/>
              <div class="coach-text">
                <p class="coach-name">{{ selectedCourseCoach?.coachName }}</p>
                <p class="coach-specialization">{{ selectedCourseCoach?.specialization }}</p>
                <p class="coach-experience">{{ selectedCourseCoach?.introduction }}</p>
              </div>
            </div>
          </div>
        </div>

        <!-- 底部：购买按钮和关闭按钮 -->
        <div class="detail-footer">
          <el-button v-if="isMember" type="primary" @click="handleBuyCourse(selectedCourse)">
            购买课程
          </el-button>
          <el-button @click="closeDetail">关闭</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.course-view {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;

  .search-container {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10px;
    margin-bottom: 20px;
    padding: 20px;
    background-color: #ffffff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    width: 80%;
    max-width: 800px;

    .search-input {
      width: 300px;
    }

    .search-type {
      width: 150px;
    }
  }

  .course-list-container {
    width: 80%;
    max-width: 1200px;
    background-color: #ffffff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

    .course-list {
      margin-bottom: 20px;
    }

    .course-card {
      cursor: pointer;
      transition: transform 0.2s ease, box-shadow 0.2s ease;
      border-radius: 8px;
      overflow: hidden;
      margin-bottom: 20px;
      min-height: 400px; /* 固定卡片高度 */
      display: flex;
      flex-direction: column;

      &:hover {
        transform: translateY(-5px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      }

      .card-header {
        display: flex;
        flex-direction: column;
        align-items: center;

        .course-image {
          width: 100%;
          height: 150px;
          object-fit: cover;
          border-radius: 8px;
          margin-bottom: 16px;
        }

        h3 {
          margin: 0;
          font-size: 18px;
          color: #303133;
        }
      }

      .info {
        p {
          margin: 4px 0;
          font-size: 14px;
          color: #606266;
        }
      }
    }

    .pagination {
      display: flex;
      justify-content: center;
      margin-top: 20px;
    }
  }

  .course-detail-dialog {
    .course-detail {
      display: flex;
      gap: 24px;
      padding-bottom: 60px; /* 为底部按钮留出空间 */
      /* 左侧：图片和课程内容 */
      .detail-left {
        flex: 1;
        max-width: 300px;
        display: flex;
        flex-direction: column;
        //align-items: center;
        .detail-header {
          text-align: center;
          margin-bottom: 20px;

          .course-image {
            width: 120px;
            height: 120px;
            border-radius: 50%;
            margin-bottom: 16px;
          }

          .header-info {
            h2 {
              margin: 0;
              font-size: 24px;
              color: #303133;
            }

            .specialization {
              margin: 8px 0;
              font-size: 16px;
              color: #606266;
            }
          }
        }

        .detail-body {
          width: 100%;
          text-align: center;

          .detail-item {
            margin-bottom: 16px;

            .label {
              font-weight: bold;
              color: #303133;
            }

            .value {
              color: #606266;
            }
          }
        }
      }

      /* 中间：其他信息 */
      .detail-center {
        flex: 1;
        max-width: 300px;
        padding: 0 20px;

        .detail-item {
          margin-bottom: 16px;

          .label {
            font-weight: bold;
            color: #303133;
          }

          .value {
            color: #606266;
          }
        }
      }

      /* 右侧：授课教练信息 */
      .detail-right {
        flex: 1;
        max-width: 300px;

        .coach-info {
          .coach-title {
            font-size: 18px;
            color: #303133;
            margin-bottom: 16px;
          }

          .coach-details {
            display: block; // 将 flex 改为 block
            .coach-avatar {
              width: 80px;
              height: 80px;
              border-radius: 50%;
              margin-bottom: 12px; // 添加间距以分隔头像和文字
            }

            .coach-text {
              .coach-name {
                margin: 0;
                font-size: 16px;
                color: #303133;
              }

              .coach-specialization,
              .coach-experience {
                margin: 4px 0;
                font-size: 14px;
                color: #606266;
              }
            }
          }
        }
      }

      /* 底部：购买按钮和关闭按钮 */
      .detail-footer {
        position: absolute;
        bottom: 20px;
        right: 20px;
        display: flex;
        gap: 10px;
      }
    }
  }
}
</style>